import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    // 列表
    list: [],

    // 文本框
    inputValue: '',

    // 下一个item的id值
    nextId: 5,

    // 总列表数
    count: 5,

    viewKey: 'all'
  },
  mutations: {
    allList: (state, list) => {
      state.list = list
      state.count = state.list.length
    },

    setInputValue: (state, val) => {
      state.inputValue = val
    },

    addItem: state => {
      const obj = {
        id: state.nextId,
        info: state.inputValue,
        done: false
      }
      state.list.push(obj)
      state.nextId++
      state.inputValue = ''
      state.count = state.list.length
    },

    deleteItem: (state, id) => {
      const index = state.list.findIndex(item => item.id === id)
      state.list.splice(index, 1)
      state.count = state.list.length
    },

    changeStatus: (state, id) => {
      if (state.list[id].done === true) {
        state.list[id].done = false
      } else {
        state.list[id].done = true
      }
    },

    clearDone: state => {
      state.list = state.list.filter(item => item.done === false)
    },

    changeView: (state, key) => {
      state.viewKey = key
    }
  },
  actions: {
    getList (context, step) {
      axios.get('/list.json').then(({ data }) => {
        context.commit('allList', data)
      })
    }
  },
  getters: {
    undoneList: state => {
      return state.list.filter(item => item.done === false).length
    },
    infoList: state => {
      if (state.viewKey === 'all') {
        return state.list
      } else if (state.viewKey === 'undone') {
        return state.list.filter(item => !item.done)
      } else if (state.viewKey === 'done') {
        return state.list.filter(item => item.done)
      }
      return state.list
    }
  }
})
